package com.example.hlddz2.repository;

import android.content.Context;
import android.content.SharedPreferences;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.example.hlddz2.model.Order;
import com.example.hlddz2.repository.CartRepository;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class OrderRepository {
    private static final String SP_NAME = "order_sp";
    private static final String KEY_ORDERS = "key_orders";
    private static OrderRepository instance;

    private final SharedPreferences sp;
    private final Gson gson = new Gson();
    private final MutableLiveData<List<Order>> ordersLive = new MutableLiveData<>();

    private OrderRepository(Context context) {
        sp = context.getApplicationContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        ordersLive.setValue(loadOrders());
    }

    public static synchronized OrderRepository getInstance(Context context) {
        if (instance == null) {
            instance = new OrderRepository(context);
        }
        return instance;
    }

    public LiveData<List<Order>> getOrders() {
        return ordersLive;
    }

    public void createOrderFromCart(List<CartRepository.CartItem> cartItems) {
        if (cartItems.isEmpty()) return;

        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setStatus("待付款");
        order.setCreateTime(new Date());

        List<Order.OrderItem> orderItems = new ArrayList<>();
        double total = 0;
        for (CartRepository.CartItem cartItem : cartItems) {
            Order.OrderItem item = new Order.OrderItem();
            item.setGoodsId(cartItem.goodsId);
            item.setName(cartItem.name);
            item.setPrice(cartItem.price);
            item.setImage(cartItem.image);
            item.setCount(cartItem.count);
            orderItems.add(item);
            total += cartItem.price * cartItem.count;
        }

        order.setItems(orderItems);
        order.setTotalPrice(total);

        List<Order> currentOrders = new ArrayList<>(ordersLive.getValue() != null ? ordersLive.getValue() : new ArrayList<>());
        currentOrders.add(order);
        saveOrders(currentOrders);
    }

    // 新增：允许外部更新订单列表
    public void saveOrders(List<Order> orders) {
        sp.edit().putString(KEY_ORDERS, gson.toJson(orders)).apply();
        ordersLive.postValue(orders);
    }

    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
    }

    private List<Order> loadOrders() {
        String json = sp.getString(KEY_ORDERS, "");
        if (json.isEmpty()) return new ArrayList<>();
        Type type = new TypeToken<List<Order>>(){}.getType();
        List<Order> orders = gson.fromJson(json, type);
        return orders != null ? orders : new ArrayList<>();
    }
}